package top.h1234.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import top.h1234.mapper.BrandMapper;
import top.h1234.pojo.Brand;
import top.h1234.util.SqlSessionFactoryUtils;

import java.util.List;

public class BrandService {
    // 1. 获取工厂对象
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    // 查询所有
    public List<Brand> SelectAll() {
        // 2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 获取mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        // 4. 执行sql
        List<Brand> brands = mapper.selectAll();
        // 5. 释放资源
        sqlSession.close();
        // 6. 返回数据
        return brands;
    }

    // 添加
    public void add(Brand brand) {
        // 2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 获取mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        // 4. 执行sql
        mapper.add(brand);
        // 提交事务
        sqlSession.commit();
        // 5. 释放资源
        sqlSession.close();
    }

    // 根据Id查询
    public Brand SelectById(int id) {
        // 2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 获取mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        // 4. 执行sql
        Brand brand = mapper.selectById(id);
        // 5. 释放资源
        sqlSession.close();
        // 6. 返回数据
        return brand;
    }

    // 根据Id修改
    public void UpdateById(Brand brand){
        // 2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 获取mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        // 4. 执行sql
        mapper.updateById(brand);
        // 提交事务
        sqlSession.commit();
        // 5. 释放资源
        sqlSession.close();
    }

    // 根据Id删除
    public void DeleteById(int id){
        // 2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 获取mapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        // 4. 执行sql
        mapper.deleteById(id);
        // 提交事务
        sqlSession.commit();
        // 5. 释放资源
        sqlSession.close();
    }
}
